/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * MyFrame.java
 *
 * Created on 25.03.2011, 15:15:03
 */

package airportmap;

import java.awt.Point;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;

/**
 *
 * @author Мама
 */
public class MyFrame extends javax.swing.JFrame {
    ArrayList<ArrayList> lines = new ArrayList();
    
    AirportPanel airportPanel;

    /** Creates new form MyFrame */
    public MyFrame() {
        initComponents();

        URL resource = this.getClass().getResource("/mysources/OBNINSK.SHP");
        try {
            InputStream is = resource.openStream();
            //airportPanel=new AirportPanel(is);
            jPanel2.add(airportPanel);
        } catch (IOException ex) {
            Logger.getLogger(MyFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jButton1 = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jButton3 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true));
        jPanel1.setLayout(new java.awt.BorderLayout());

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);

        jPanel1.add(jScrollPane1, java.awt.BorderLayout.CENTER);

        jButton1.setText("Open map");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jPanel2.setBackground(new java.awt.Color(255, 255, 255));
        jPanel2.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED, java.awt.Color.darkGray, java.awt.Color.pink, null, null));
        jPanel2.addMouseWheelListener(new java.awt.event.MouseWheelListener() {
            public void mouseWheelMoved(java.awt.event.MouseWheelEvent evt) {
                jPanel2MouseWheelMoved(evt);
            }
        });
        jPanel2.setLayout(new java.awt.BorderLayout());

        jButton3.setText("Start");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 279, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(10, 10, 10)
                        .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, 564, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton1)
                        .addGap(84, 84, 84)
                        .addComponent(jButton3)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 611, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 611, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton3))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    
    public static byte[] getBytesFromFile(File file) throws IOException {
        InputStream is = new FileInputStream(file);

        // Get the size of the file
        long length = file.length();

        // You cannot create an array using a long type.
        // It needs to be an int type.
        // Before converting to an int type, check
        // to ensure that file is not larger than Integer.MAX_VALUE.
        if (length > Integer.MAX_VALUE) {
            // File is too large
        }

        // Create the byte array to hold the data
        byte[] bytes = new byte[(int)length];

        // Read in the bytes
        int offset = 0;
        int numRead = 0;
        while (offset < bytes.length
               && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
            offset += numRead;
        }

        // Ensure all the bytes have been read in
        if (offset < bytes.length) {
            throw new IOException("Could not completely read file "+file.getName());
        }

        // Close the input stream and return bytes
        is.close();
        return bytes;
    }

    private int byteArrayToInt(byte[] b, int start, int length) {
        int dt = 0;
        if ((b[start] & 0x80) != 0)
            dt = Integer.MAX_VALUE;
        for (int i = 0; i < length; i++)
            dt = (dt << 8) + (b[start++] & 255);
        return dt;
    }

    private byte[] intToByteArray(int n, int byteCount) {
        byte[] res = new byte[byteCount];
        for (int i = 0; i < byteCount; i++)
            res[byteCount - i - 1] = (byte) ((n >> i * 8) & 255);
        return res;
    }

    private int readLittleEndianInt(InputStream is) throws IOException{
        byte[] b=new byte[4];
        is.read(b);
        return byteArrayToInt(b,0,4);
    }

    private int readBigEndianInt(InputStream is) throws IOException{
        byte[] b=new byte[4];
        is.read(b);
        byte[] b2=new byte[4];
        for(int i=0;i<4;i++)
            b2[i]=b[3-i];
        return byteArrayToInt(b2,0,4);
    }

    private double readLittleEndianDouble(InputStream is) throws IOException{
        byte[] bdouble = new byte[8];
        is.read(bdouble);
        // read into bdouble ...

        long longBits = ((long)bdouble[0] << 56) +
            ((long)(bdouble[1] & 255) << 48) +
            ((long)(bdouble[2] & 255) << 40) +
            ((long)(bdouble[3] & 255) << 32) +
            ((long)(bdouble[4] & 255) << 24) +
            ((bdouble[5] & 255) << 16) +
            ((bdouble[6] & 255) <<  8) +
            ((bdouble[7] & 255) <<  0);

        double d = java.lang.Double.longBitsToDouble(longBits);

        return d;
    }

    private double readBigEndianDouble(InputStream is) throws IOException{
        byte[] bdouble = new byte[8];
        byte[] b2 = new byte[8];
        is.read(b2);
        // read into bdouble ...
        
        for(int i=0;i<8;i++)
            bdouble[i]=b2[7-i];
        long longBits = ((long)bdouble[0] << 56) +
            ((long)(bdouble[1] & 255) << 48) +
            ((long)(bdouble[2] & 255) << 40) +
            ((long)(bdouble[3] & 255) << 32) +
            ((long)(bdouble[4] & 255) << 24) +
            ((bdouble[5] & 255) << 16) +
            ((bdouble[6] & 255) <<  8) +
            ((bdouble[7] & 255) <<  0);
        
        double d = java.lang.Double.longBitsToDouble(longBits);

        return d;
    }

    
    private void jPanel2MouseWheelMoved(java.awt.event.MouseWheelEvent evt) {//GEN-FIRST:event_jPanel2MouseWheelMoved
        System.out.println(""+evt.getWheelRotation());
        airportPanel.wheel(evt.getWheelRotation()*(-1), (double)evt.getX(), (double)evt.getY());
    }//GEN-LAST:event_jPanel2MouseWheelMoved

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        
        airportPanel.startMove();
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        JFileChooser f = new JFileChooser();
        int res = f.showOpenDialog(this);
        // /home/oleg/Документы/roadl/ROADL.SHP
        if(res==JFileChooser.APPROVE_OPTION){
            try {
                long read=0;
                jTextArea1.append(f.getSelectedFile().getPath()+"\n");
                File file = f.getSelectedFile();
                FileInputStream is = new FileInputStream(file);
                long len = file.length();

                for(int i=0;i<7;i++){
                    jTextArea1.append(readLittleEndianInt(is)+",");
                }
                for(int i=0;i<2;i++){
                    jTextArea1.append(readBigEndianInt(is)+",");
                }
                for(int i=0;i<8;i++){
                    jTextArea1.append(readBigEndianDouble(is)+",");
                }
                byte[] tmp = new byte[1000];

                read=100;

                // один цикл - одна запись в *.SHP
                while(read<len){
                    ArrayList<Point> newLines = new ArrayList();
                    int recNum = readLittleEndianInt(is); read+=4;
                    int recLen = readLittleEndianInt(is); read+=4;
                    int recType = readBigEndianInt(is); read+=4;

                    jTextArea1.append("\n"+recNum+"_"+recLen+": "+recType);


                    jTextArea1.append(",");
                    for(int j=0; j< 4; j++){
                        jTextArea1.append(readBigEndianDouble(is)+" "); read+=8;
                    }
                    jTextArea1.append(",");
                    int numParts = readBigEndianInt(is); read+=4;
                    int numPoints = readBigEndianInt(is); read+=4;
                    jTextArea1.append(numParts+", "+numPoints+", ");
                    for(int j=0;j<numParts; j++){
                        jTextArea1.append(readBigEndianInt(is)+" "); read+=4;
                    }
                    jTextArea1.append(",");
                    for(int j=0;j<numPoints; j++){
                        double x=readBigEndianDouble(is);
                        double y=readBigEndianDouble(is);
                        Point point = new Point();
                        point.setLocation(x, y);
                        newLines.add(point);
                        jTextArea1.append("("+x+";"+y+"),"); read+=16;
                    }
                    jTextArea1.append("\n");
                    lines.add(newLines);
                }

                airportPanel.setLines(lines);

            } catch (IOException ex) {
                Logger.getLogger(MyFrame.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
}//GEN-LAST:event_jButton1ActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MyFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    // End of variables declaration//GEN-END:variables

}
